<template>
	<simple-layout
		class="vjointag"
		ref="simpleLayoutRef"
		:isShowSearch="false"
		:isUseCheck="false"
		:isDisabled="true"
		itemLabelField="name"
		@toSwitchAccount="onSwitchAccount"
	>
		<template #content>
			<transfer-tree
				:checkable="true"
				:defaultExpandedKeys="defaultExpandedKeys"
				:checkedList="checkedList"
				:treeData="treeData"
				:isUseDefaultIcon="false"
				:isCustomIcon="true"
				@toCheckedNode="onChecked"
			></transfer-tree>
		</template>
	</simple-layout>
</template>

<script>
import simpleLayout from '@/components/simpleLayout.vue';
import transferTree from '@/components/transferTree.vue';

import { mapActions, mapState } from 'vuex';
import { EntityTypes } from '@/utils/orgConstants';

import { getPanelData } from '@/api/modules/SelectOrgApi';
import { ACTION_TOGGLE_ENTITY } from '@/store/actionTypes';

export default {
	name: 'JoinAccountTag',
	components: {
		simpleLayout,
		transferTree
	},
	inject: ['app'],
	data() {
		return {
			treeData: [],
			checkedList: [],
			defaultExpandedKeys: []
		};
	},
	computed: {
		...mapState('selectData', ['selectedEntityMap'])
	},
	watch: {
		selectedEntityMap: {
			deep: true,
			handler(selectedEntity) {
				this.onTreeNodeCheckedList(selectedEntity);
			}
		}
	},
	methods: {
		...mapActions('selectData', [ACTION_TOGGLE_ENTITY]),
		async onGetPanelData(data = {}) {
			let params = {
				command: 'vjoinAccountTagTree',
				panel: 'JoinAccountTag',
				arguments: data
			};
			let res = await getPanelData(params);
			if (res.code !== 0) {
				this.treeData = [];
				return;
			}
			let treeData = res.data;
			this.dealNodeCheckbox(treeData);
			if (treeData.length) {
				this.$set(this.defaultExpandedKeys, 0, treeData[0].id);
			}
			this.treeData = treeData;
		},
		/**
		 * 处理部分节点不能用Checkbox
		 * @param nodes 节点
		 */
		dealNodeCheckbox(nodes) {
			for (let node of nodes) {
				node.disabled = !(node.type.indexOf(EntityTypes.TP_OrgMetadataTag) === -1);
				if (node.children && node.children.length) {
					this.dealNodeCheckbox(node.children);
				}
			}
		},
		onChecked(data) {
			if (data.checkeds.length) {
				let type = data.checkeds[0].type;
				if (type.indexOf(EntityTypes.TP_OrgMetadataTag) === -1) {
					// TP_开头的数据不能被选择
					this[ACTION_TOGGLE_ENTITY]({
						entities: data.checkeds
					});
				}
			}
		},
		onSwitchAccount(data) {
			this.onGetPanelData();
		},
		onTreeNodeCheckedList(selectedEntity) {
			let checkedList = [];
			let typeIds = Object.keys(selectedEntity);
			for (let item of typeIds) {
				if (item.indexOf(EntityTypes.JoinAccountTag) !== -1) {
					checkedList.push(item.split('|')[1]);
				}
			}
			this.checkedList = checkedList;
		},
		onChangeAccount(data) {
			this.$refs.simpleLayoutRef.onChangeAccount(data);
		}
	},
	created() {
		this.onTreeNodeCheckedList(this.selectedEntityMap);
		this.onGetPanelData();
	}
};
</script>

<style scoped lang="scss">
.vjointag  {
	border: 1px solid $borderColor;
	border-right: 0;
}
</style>
